#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
"""
@File    :   login.py
@Time    :   2023/11/15 17:31:13
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib
from datetime import datetime
from django.contrib.auth import authenticate
from django.forms import model_to_dict
from ninja import Schema, Router

from system.models import SimpleOperationLog
from utils.enums import OperationMethod, OperationObject
from utils.response import Response
from utils.jwt import Jwt
from backend.settings import SECRET_KEY, TOKEN_LIFETIME


router = Router()


# 用户登录请求字段
class LoginSchemaIn(Schema):
    username: str
    password: str


# 用户登录
@router.post("/login", auth=None)
def login(request, loginInfo: LoginSchemaIn):
    """
    函数功能：用户登录函数

    参数：
    - request: 请求对象
    - loginInfo: 包含用户名和密码的LoginSchemaIn对象

    返回：
    - Response对象,包含登录结果信息和用户信息及token

    """
    # 调用authenticate函数验证用户名和密码
    user_obj = authenticate(username=loginInfo.username, password=loginInfo.password)

    if user_obj:
        # 获取用户角色列表
        role = user_obj.role.all().values("id")
        role_list = []
        for item in role:
            role_list.append(item["id"])

        # 将用户对象转换为字典
        user_obj_dic = model_to_dict(user_obj)
        user_obj_dic['role'] = role_list

        # 移除字典中不需要的字段
        del user_obj_dic["password"]
        del user_obj_dic["avatar"]

        # 获取当前时间戳和token的有效期
        time_now = int(datetime.now().timestamp())
        jwt = Jwt(SECRET_KEY, user_obj_dic, valid_to=time_now + TOKEN_LIFETIME)

        # 构建返回的data字典
        data = {
            "multi_depart": 1,
            "sysAllDictItems": "q",
            "departs": "e",
            "userInfo": user_obj_dic,
            "token": jwt.encode(),
        }
        SimpleOperationLog.add_log(
            request,
            user_obj.pk,
            OperationObject.user,
            OperationMethod.login_by_account,
            f"用户登陆(ID={user_obj.pk})",
        )
        # 返回登录成功的Response对象
        return Response(code=200, msg="登录成功", data=data)
    else:
        # 返回登录失败的Response对象
        return Response(code=500, msg="账号或者密码错误")
